package com.ramms.eater.parser.base;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public abstract class AbstractParser<T> {

	private List<T> items = null;
	private String url;
	private String tag;
	
	public AbstractParser(String url, String tag) {
		this.url = url;
		this.tag = tag;
	}

	public void parser() {
		
		URL url = null;
		HttpURLConnection conn = null;
		
		this.items = new ArrayList<T>();
		
        try {
        	
        	url = new URL(this.url);

        	conn = (HttpURLConnection) url.openConnection();

        	if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        		
        		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        		DocumentBuilder db = dbf.newDocumentBuilder();
        		Document doc;
        		
	            doc = db.parse(url.openStream());
	            doc.getDocumentElement().normalize();

	            NodeList itemLst = doc.getElementsByTagName(tag);
	
	            for (int i = 0 ; i < itemLst.getLength() ; i++) {
                    Node item = itemLst.item(i);
                    if (item.getNodeType() == Node.ELEMENT_NODE) {
                    	Element ielem = (Element) item;
                    	items.add(getItem(ielem));
                    }
	            }
        	}
        	
	    } catch (MalformedURLException e) {
		    e.printStackTrace();
		} catch (DOMException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		} catch (ParserConfigurationException e) {
		    e.printStackTrace();
		} catch (SAXException e) {
		    e.printStackTrace();
	    } finally {
	    	if(conn != null)
	    		conn.disconnect();			
		}
	}
	
	public abstract T getItem(Element e);

	public List<T> getItems() {
		return items;
	}

	public void setItems(List<T> items) {
		this.items = items;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getTag() {
		return tag;
	}

	public void setTag(String tag) {
		this.tag = tag;
	}
	
}
